//
//  SearchViewController.swift
//  CJXSwiftStoryboard
//
//  Created by CJX on 2016/10/26.
//  Copyright © 2016年 caijianxi. All rights reserved.
//



import UIKit
import SVProgressHUD
import MJRefresh
class SearchViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {
    
    var pageNumber :String = "1"
    var page : Int = 1
    
    var keyWord : String?
    
    
    let COLLECTIONVIEWCELL = "ProductCollectionCell"
    
    
    var dataArray = NSMutableArray(capacity: 0)
    
    var myCollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewLayout())
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "THE SEARCH RESULTS"
        
        self.automaticallyAdjustsScrollViewInsets = false
        self.view.backgroundColor = UIColor.white
        
        self.getData()
        self.creatView()
        
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        sideMenuViewController()?.menuContainerView?.allowPanGesture = false
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}


extension SearchViewController{
    fileprivate func getData(){
        self.pageNumber = String(self.page)
        let prama = ["main_page":"advanced_search_result","keyword":self.keyWord!,"page":self.pageNumber]
        NetworkTool.shareInstance.request(.get, urlString: APIBASE, parmas: prama as [String : NSObject]) { (result, error) in
            if result != nil{
                //                print(result)
                let dic = (result as? NSDictionary)!["data"] as? NSDictionary
                let totalPage = dic!["total_pages"] as? NSNumber
                let array = dic!["products_list"]as?[[String:NSObject]]
                
                
                
                if self.page>Int(totalPage!){
                    SVProgressHUD.showSuccess(withStatus: "Finish download data.")
                    
                }else{
                    for dict in array!{
                        let model = ProductModel(dict: dict)
                        self.dataArray.add(model)
                    }
                    self.myCollectionView.reloadData()
                    SVProgressHUD.showSuccess(withStatus: "Load successfully!")
                }
                
                
                self.myCollectionView.mj_header.endRefreshing()
                self.myCollectionView.mj_footer.endRefreshing()
            }else{
                SVProgressHUD.showError(withStatus: "productList error:" + String(describing: error))
                print("productList error:" + String(describing: error))
            }
        }
        
    }
}

extension SearchViewController{
    fileprivate func creatView(){
        
        let leftBtn = UIButton(type: .custom)
        leftBtn.setImage(UIImage(named: "nav_back"), for: UIControlState())
        leftBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        leftBtn.addTarget(self, action: #selector(leftBtnClick), for: .touchUpInside)
        let item = UIBarButtonItem(customView: leftBtn)
        self.navigationItem.leftBarButtonItem = item
        
        
        
        
        
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: (SCREEN_WIDTH-15)/2, height: (SCREEN_WIDTH-15)/2*1.3)
        layout.minimumInteritemSpacing = 4
        layout.minimumLineSpacing = 4
        layout.sectionInset = UIEdgeInsetsMake(5, 5, 0, 5)
        
        myCollectionView.backgroundColor = UIColor.white
        myCollectionView.collectionViewLayout = layout
        myCollectionView.frame = CGRect(x: 0, y: 64, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-64)
        myCollectionView.delegate = self
        myCollectionView.dataSource = self
        self.view.addSubview(myCollectionView)
        myCollectionView.register(ProductListCollectionViewCell.self, forCellWithReuseIdentifier: COLLECTIONVIEWCELL)
        
        
        myCollectionView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            SVProgressHUD.show(withStatus: "Loading...")
            self.page = 1
            self.dataArray.removeAllObjects()
            self.getData()
        })
        myCollectionView.mj_footer = MJRefreshBackFooter(refreshingBlock: {
            SVProgressHUD.show(withStatus: "Loading...")
            self.page = self.page + 1
            self.getData()
            
        })
        
        
        
    }
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: COLLECTIONVIEWCELL, for: indexPath)
        let model = self.dataArray[indexPath.item]as?ProductModel
        
        (cell as? ProductListCollectionViewCell)?.model = model
        
        return cell
        
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let commodityVC = CommodityViewController()
        let model = self.dataArray[indexPath.item] as? ProductModel
        commodityVC.idStr = model!.products_id
        commodityVC.productImgView = model!.products_image!
        self.navigationController?.pushViewController(commodityVC, animated: true)
        
        
    }
    
    
    
    
    func leftBtnClick(){
        self.navigationController?.popViewController(animated: true)
    }
    
}















